#include <Arduino.h>
#include <Ds1302.h>

// put function declarations here:
Ds1302 rtc(2, 4, 3);
bool receiving = false;
String cmd;
uint8_t parseDigits(char *str, uint8_t count);

void setup()
{
  // put your setup code here, to run once:
  rtc.init();

  Serial.begin(9600);
  Serial.print("compiled: ");
  Serial.print(__DATE__);
  Serial.println(__TIME__);
  Serial.println("send yyMMddHHmmss set time");
}

void loop()
{
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0)
  {
    if (!receiving)
    {
      Serial.print("receiving...");
    }
    receiving = true;

    if (Serial.peek() != '\n')
    {
      cmd += (char)Serial.read();
    }
    else
    {
      Serial.println("Done");
      Serial.read();
      Serial.print("received:");
      Serial.println(cmd);

      Ds1302::DateTime dt;

      char buffer[13];
      cmd.toCharArray(buffer, cmd.length() + 1);
      dt.year = parseDigits(buffer, 2);
      dt.month = parseDigits(buffer + 2, 2);
      dt.day = parseDigits(buffer + 4, 2);
      dt.hour = parseDigits(buffer + 6, 2);
      dt.minute = parseDigits(buffer + 8, 2);
      dt.second = parseDigits(buffer + 10, 2);

      // set the date and time
      rtc.setDateTime(&dt);

      receiving = false;
    }
  }
  if (!receiving)
  {
    Ds1302::DateTime dt;
    rtc.getDateTime(&dt);
    char buf[50];
    snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d", dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second);
    Serial.print("current time:");
    Serial.println(buf);
  }
  delay(1000);
}

// put function definitions here:
uint8_t parseDigits(char *str, uint8_t count)
{
  uint8_t val = 0;
  while (count-- > 0)
    val = (val * 10) + (*str++ - '0');
  return val;
}